<style>
.text {
  font-size: 16px;
}

.clearfix{
  background-color: #F9F9F9;
  color: #666666;
  font-weight: bold;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.el-card__header{
  background-color: #F9F9F9;
}
.box-card {
  width: 100%;
  margin: auto;
  margin-bottom: 10px;
}
.foot{
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  position: fixed;
  bottom: 0;
  background-color: #fff;
  width: calc(100vw - 200px);
  right: 0;
}
.app-container{
  position: relative;
}

.el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
      </div>
      <div class="text item">
<!--        <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--          <el-row>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="敏感词">-->
<!--                <el-input v-model="upload.sensitiveWords" :rows="5" type="textarea" placeholder="请输入内容,一行一个词"></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="全局库存">-->
<!--                <el-input v-model="upload.kucun" placeholder=""></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
<!--        </el-form>-->
        <div slot="footer" class="dialog-footer" style="text-align: left;margin-bottom: 15px;margin-top: 10px;display: flex">
          <el-button type="primary" icon="el-icon-upload2"  :disabled="isDis" size="mini" @click="openFile">导入数据</el-button>
<!--          <el-button type="info" icon="el-icon-house"  :disabled="isDis" size="mini" @click="fenpei">分配店铺</el-button>-->
          <el-button type="success" icon="el-icon-check"  :disabled="isDis" size="mini" @click="startUpload">开始上传</el-button>
          <el-button type="warning" icon="el-icon-close"  :disabled="isDis" size="mini" @click="endUpload">停止上传</el-button>
          <el-button type="danger" icon="el-icon-refresh-right"  :disabled="isDis" size="mini" @click="clearData">清空数据</el-button>
          <span v-show="progShow" style="margin-left: 10px;">任务进度:</span><el-progress  v-show="progShow"  :text-inside="true" :stroke-width="14" :percentage="progress" style="width: 40%;margin-left: 10px" status="success"></el-progress>
          <span v-show="progShow" style="margin-left: 10px">{{ minNum }}/ {{ maxNum }}</span>
        </div>
        <el-table v-loading="loading" border :data="dataList">
          <el-table-column label="抖音id" align="center" prop="product_id" />
          <el-table-column label="标题" width="150" show-overflow-tooltip align="center" prop="title" />
          <el-table-column label="封面" width="50" align="center" prop="cover" >
              <template scope="scope">
                  <img :src="scope.row.cover" style="width: 25px;width: 25px">
              </template>
          </el-table-column>
          <el-table-column label="货源平台" width="100" align="center"  :show-overflow-tooltip="true" >
            <span>抖音</span>
          </el-table-column>
          <el-table-column label="店铺名称" align="center"  :show-overflow-tooltip="true" >
            <span>{{mallName}}</span>
          </el-table-column>
          <el-table-column label="设置必填项" align="center"  >
            <template scope="scope">
              <el-button type="primary" size="small" @click="setbTX(scope.row)">设置</el-button>
            </template>
          </el-table-column>
          <el-table-column label="上传状态" align="center" prop="msg"  :show-overflow-tooltip="true" />
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
        </el-table>
        <el-dialog title="选择文件" :visible.sync="goodsopen" width="800px" append-to-body>
          <el-row>
            <el-col :span="12">
              <el-upload
                ref="upload"
                :limit="1"
                accept=".txt"
                :headers="upload.headers"
                :action="upload.url + '?mallId=' + upload.mallId"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <el-table v-loading="loading" border :data="mallList">
                <el-table-column label="选择" align="center" width="60">
                  <template slot-scope="scope">
                    <el-radio v-model="upload.mallId" :label="scope.row.mallId"
                              @change.native="handleSelectionChange(scope.row, scope.$index)"
                    >
                      <label></label>
                    </el-radio>
                  </template>
                </el-table-column>
                <el-table-column label="logo" align="center" prop="logo" >
                  <template slot-scope="scope">
                    <ImagePreview
                      :width=40 :height=40
                      :src="scope.row.logo"
                      :preview-src-list="[scope.row.logo]"/>
                  </template>
                </el-table-column>
                <el-table-column label="店铺名称" align="center" key="mallName" prop="mallName"  :show-overflow-tooltip="true" />
                <el-table-column label="店铺描述" align="center" key="mallDesc" prop="mallDesc"  :show-overflow-tooltip="true" />
              </el-table>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="upload.isUploading" @click="submitFileForm">确 定</el-button>
            <el-button :disabled="upload.isUploading" @click="cancelFile">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
    <el-dialog title="必填项设置" :visible.sync="btxopen" width="1000px" append-to-body>
      <el-form ref="form" :model="rowData" label-width="150px">
        <el-row>
          <el-col :span="8" v-for="item in rowData.goodsPropertiesRule.properties">
            <el-form-item
              :label="item.name"
              :rules="[{ required:item.required, message: '数据不能为空'}]"
            >
              <el-select v-model="item.vid" @change="changeSx(item.name,item.refPid,item.values,item.vid)" v-if="item.values!=null">
                <el-option
                  v-for="sele in item.values"
                  :key="sele.vid"
                  :label="sele.value"
                  :value="sele.vid"
                ></el-option>
              </el-select>
              <el-input v-else maxlength="50" v-model="item.val" @change="findvalue(item.name,item.refPid,item.val)" style="width: 70%;"/>
              <el-select style="width: 30%;"  v-model="item.value_unit" @change="changeUnit" v-if="item.valueUnit[0]!=''">
                <el-option
                  v-for="Unit in item.valueUnit"
                  :key="Unit"
                  :label="Unit"
                  :value="Unit"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="满两件折扣">
              <el-input maxlength="50" v-model="sku.manliangjian"  style="width: 70%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="规格">
              <el-select v-model="sku.parentSpecId" @change="changeGg()">
                <el-option
                  v-for="sele in goodsSpecList"
                  :key="sele.parentSpecId"
                  :label="sele.parentSpecName"
                  :value="sele.parentSpecId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-button @click="addDomain">新增规格</el-button>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              v-for="(domain, index) in sku.ggs"
              :label="'规格' + index"
              :key="domain.key"
              :prop="'domains.' + index + '.value'"
              :rules="{
               required: true, message: '规格名称不能为空', trigger: 'blur'}">
              <el-input v-model="domain.value"></el-input>
              <el-button @click.prevent="removeDomain(domain)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table border :data="sku.ggs">
              <el-table-column show-overflow-tooltip prop="value" label="规格名称" align="center" width="120"/>
              <el-table-column show-overflow-tooltip label="库存" align="center" prop="kc">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.kc"></el-input>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="拼单价(元)" align="center" prop="pdj">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.pdj"></el-input>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="单买价(元)" align="center" prop="dmj">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.dmj"></el-input>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="预览图" align="center" prop="ylt">
                <template slot-scope="scope">
<!--                  <el-input v-model="scope.dmj"></el-input>-->
                  <el-upload
                    class="upload-demo"
                    ref="upload"
                    :limit="1"
                    accept=".png"
                    :headers="upload.headers"
                    :action="uploadUrl + '?mallId=' + upload.mallId"
                    :disabled="upload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccessslt"
                    :auto-upload="true"
                     >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="规格编码" align="center" prop="ggbm">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ggbm"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="saveSkuData">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {getToken} from "@/utils/auth";
import {listMall} from "@/api/system/mall";
import {uploadGoods,findRoleData,findvalueSearch,findspecGet} from "@/api/system/pddGoods";

import Template from "@/views/system/pddtemplate/index";

export default {
  name: "Goods",
  components: {Template},
  dicts: ['sys_orderbys'],
  data() {
    return {
      // 遮罩层
      loading: false,
      progShow:false,
      btxopen:false,
      maxNum:0,
      minNum:0,
      progress:0,
      // 选中数组
      ids: [],
      dataList:[],
      mallList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 抖音商品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      mallopen: false,
      goodsopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "抖音商品id不能为空", trigger: "blur" }
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "商品批量上传",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pdd/pddGoodsUpload",
        titleWords : "",
        mallId:""
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/pdd/pddGoodsUploadslt",
      categoryOptions:[],
      iszx:'0',
      isSHOW:true,
      isDis: false,
      active:1,
      currentPage: 1,       // 当前页码
      pageNum: 1,
      pageSize: 10,
      mallName:"",
      mallId:"",
      radio:null,
      socket: null,
      // 定义一个队列来存储待发送的数据
      dataQueue : [],
      sending : false, // 标记是否正在发送数据
      category_id:"",
      category_id3:"",
      rowData: {
        goodsPropertiesRule:{
          properties:[]
        }
      },
      sku:{
        sku_properties:[],
        ggs:[],
        manliangjian:""
      },
      goodsSpecList:[],
      product_id:""
    };
  },
  created() {
    this.getMallList();
    this.initSocket();
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  },
  methods: {
    /** 查询抖音商品列表 */
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productId: null,
        categoryId: null,
        categoryName: null,
        title: null,
        cover: null,
        price: null,
        status: null,
        addTime: null,
        upTime: null,
        labelIds: null,
        shopName: null,
        commentNum: null,
        commentScore: null,
        couponPrice: null,
        inStock: null,
        kolNum: null,
        sales: null,
        hasSxt: null,
        detailUrl: null,
        orderNum: null,
        firstCid: null,
        secondCid: null,
        shopId: null,
        thirdCid: null,
        isAssured: null,
        twohour: null,
        oneday: null,
        week: null,
        month: null,
        activityCosRatio: null,
        corpId: null,
        promotionStartTime: null,
        promotionEndTime: null,
        originPrice: null,
        productStock: null,
        createTime: null,
        createBy: null
      };
      this.resetForm("form");
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if(response.code !=200){
        this.$modal.msgError(response.msg);
        this.isDis = false;
        return ;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", { dangerouslyUseHTMLString: true });
      // this.getList();
      this.goodsopen = false;
      this.dataList = response.data;
    },
    handleFileSuccessslt(response, file, fileList){
      console.log(response)
    },
    handleImport() {
      this.upload.title = "商品上传";
      this.upload.open = true;
    },
    submitFileForm() {
      if(this.mallId=="" || this.mallId === undefined){
        this.$modal.msgWarning("请选择上传店铺！");
        return ;
      }
      this.upload.mallId = this.mallId;
      this.$refs.upload.submit();
    },
    shangyibu(){
      this.active--;
    },
    getList(){
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.visibleGoodsList = this.goodsList.slice(start, end);
    },
    fenpei(){
      this.mallopen = true;
    },
    getMallList() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageNum = 100;
      listMall(this.queryParams).then(response => {
        this.mallList = response.rows;
      });
    },
    handleSelectionChange(data){
      this.mallName = data.mallName;
      this.mallId = data.mallId;
    },
    openFile() {
      this.goodsopen = true;
    },
    cancelFile(){
      this.goodsopen = false;
    },
    // 开始上传
    startUpload() {
      this.progShow = true;
      this.maxNum = this.dataList.length;
      var json = {};
      // this.loading = true;
      json.tlDyDoodsDetails = this.dataList;
      json.mallId = this.upload.mallId;
      this.dataList = [];
      uploadGoods(json).then(response => {
        console.log(response);
      });
    },
    clearData(){

    },
    endUpload(){

    },
    initSocket(){
      var _this = this;
      this.socket = new WebSocket(`ws://localhost:8080/ws/${this.$store.getters.userId}`); // 将用户ID动态拼接到WebSocket地址中

      // 监听 WebSocket 连接打开事件
      this.socket.onopen = function(event) {
        console.log("WebSocket 连接已打开");
        // 每隔一定时间发送心跳包
        setInterval(() => {
          _this.sendHeartbeat();
        }, 10000); // 例如，每隔 30 秒发送一次心跳包
      };

      this.socket.onmessage = (event) => {
        console.log('Message received:', event.data);
        var res = JSON.parse(event.data);
        var data = res.data;
        data.msg = res.msg;
        this.dataList.push(data);
        this.maxNum = res.sumNum;
        this.minNum = res.cuNum;
        this.progress = Math.floor((this.minNum / this.maxNum) * 100);
        // 处理收到的消息
      };

      this.socket.onclose = () => {
        console.log('WebSocket closed');
        // 连接关闭后的处理
        console.log("WebSocket 连接已关闭");
        // 在连接关闭时执行断线重连的逻辑
        // 例如，延迟一段时间后重新创建 WebSocket 连接
        setTimeout(function() {
          _this.initSocket(); // 重新创建 WebSocket 连接
        }, 3000); // 例如，延迟 3 秒后重新连接
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        // 错误处理
      };
    },
    sendHeartbeat() {
      if (this.socket.readyState === WebSocket.OPEN) {
        // 如果 WebSocket 连接处于打开状态，则发送心跳包
        this.socket.send(JSON.stringify({heartbeat:"1"}));
      }
    },
    setbTX(row){
      findRoleData(row.category_id,this.upload.mallId).then( res =>{
         this.category_id = row.category_id;
         this.category_id3 = row.categoryId3;
         this.product_id = row.product_id;
         this.btxopen = true;
         this.rowData = res.data.catRuleGetResponse;
         this.findspecGet();
      })
    },
    saveSkuData(){
      const selectedItem = this.dataList.findIndex(item => item.product_id === this.product_id);
      this.dataList[selectedItem].pddggs = this.sku.ggs;
      this.dataList[selectedItem].parentSpecId = this.sku.parentSpecId;
      this.dataList[selectedItem].sku_properties = this.sku.sku_properties;
      this.dataList[selectedItem].manliangjian = this.sku.manliangjian;
      this.btxopen = false;
    },
    changeSx(name,refPid,values,vid){
      console.log(name)
      console.log(refPid)
      console.log(vid)
      console.log(values)
      // 通过选中的 value 找到对应的 label
      const selectedItem = values.find(item => item.vid === vid);
      var skupro = {};
      skupro.vid = vid;
      skupro.value = selectedItem.value;
      skupro.punit = name;
      skupro.ref_pid = refPid;
      var existingIndex = this.sku.sku_properties.findIndex(item => item.ref_pid === refPid);
      if (existingIndex !== -1) {
        // 如果存在相同 vid 的元素，则替换
        this.sku.sku_properties[existingIndex] = skupro;
      } else {
        // 如果不存在相同 vid 的元素，则新增
        this.sku.sku_properties.push(skupro);
      }
      console.log(this.sku)
    },
    changeUnit(){

    },
    findvalue(name,refPid,val){
      // var skupro = {};
      // skupro.mallId = this.upload.mallId;
      // skupro.refPid = refPid;
      // skupro.value = val;
      // skupro.cid = this.category_id3;
      // console.log(skupro)
      // findvalueSearch(skupro).then( res =>{
      //   console.log(res)
      //
      // })
      var skupro = {};
      skupro.value = val;
      skupro.punit = name;
      skupro.ref_pid = refPid;
      var existingIndex = this.sku.sku_properties.findIndex(item => item.ref_pid === refPid);
      if (existingIndex !== -1) {
        // 如果存在相同 vid 的元素，则替换
        this.sku.sku_properties[existingIndex] = skupro;
      } else {
        // 如果不存在相同 vid 的元素，则新增
        this.sku.sku_properties.push(skupro);
      }
    },
    findspecGet(){
      var skupro = {};
      skupro.mallId = this.upload.mallId;
      skupro.cid = this.category_id;
      console.log(skupro)
      findspecGet(skupro).then( res =>{
        console.log(res)
        this.goodsSpecList = res.data.goodsSpecGetResponse.goodsSpecList
      })
    },
    changeGg(){

    },
    removeDomain(item) {
      var index = this.sku.ggs.indexOf(item)
      if (index !== -1) {
        this.sku.ggs.splice(index, 1)
      }
    },
    addDomain() {
      this.sku.ggs.push({
        value: '',
        key: Date.now(),
        kc:"",
        pdj:"",
        dmj:"",
        ylt:"",
        ggbm:""
      });
    }
  }
};
</script>
